package com.wzq.web.filedownupload;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet("/upload.do")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、创建对象
        SmartUpload su = new SmartUpload();
        //2、初始化
        su.initialize(getServletConfig(),req,resp);
        //3、设置编码
        su.setAllowedFilesList("jpg,png");
        //4、开始上传文件到服务器 此时还没保存
        try {
            su.upload();
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        //5、获取文件名 和 路径
        String path = "img/";
        File file = su.getFiles().getFile(0);
        //避免中文乱码
        String fileName = new String(file.getFileName().getBytes("gbk"),"utf-8");
        //6、保存文件到服务器指定路径
        try {
            file.saveAs(path+fileName,SmartUpload.SAVE_VIRTUAL);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        //7、跳转页面
        req.setAttribute("fileName",fileName);
        req.getRequestDispatcher("success.jsp").forward(req,resp);
        //下载的时候需要设置为附件，就会弹出对话框
        //su.setContentDisposition("attachment;filename="+fileName);
    }
}
